import router from "./index"
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from "@/store"

NProgress.configure({ showSpinner: false }) // 加载时不加载小图标
const whitePath = ["/login"]   // 路由白名单
router.beforeEach((to, from, next) => {
  NProgress.start() // 开始加载
  document.title = to.meta.title // 设置页面名称
  determineTheroute(to, from, next)
})

// 判断路由
function determineTheroute(to, from, next) {
  // 白名单不用登陆，即可进入
  if (whitePath.indexOf(to.path) !== -1) {
    if (store.getters.token) {
      // 获取userinfo
      store.dispatch('user/getuserinfo')
      if (to.path === '/login') {
        document.title = from.meta.title // 设置页面名称
        next('/')
      } else {
        next()
      }
    } else {
      // 未登录直接跳转到 /login
      if (to.path === '/login') {
        next()
      } else {
        next('/login')
      }
    }
  } else if (store.getters.token) {
    // 获取userinfo
    store.dispatch('user/getuserinfo')
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 未登录直接跳转到 /login
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
}


// router.afterEach(() => {
//   console.log('路由跳转完毕')
// })
